﻿using System;
using System.Collections.Generic;
using System.Threading;
using BSDS.Core.Infrastructure.Logging;
using BSDS.Service.Configuration;

namespace BSDS.Service.Logic
{
    public class SchedulingProcessor
    {
        private readonly Logger logger;
        private readonly CommandExecutor commandExecutor;
        private readonly AutoExecutionOptions options;

        public SchedulingProcessor(Logger logger, CommandExecutor commandExecutor, AutoExecutionOptions options)
        {
            this.logger = logger;
            this.commandExecutor = commandExecutor;
            this.options = options;
        }

        public void Initialize()
        {
            ThreadPool.QueueUserWorkItem(s =>
            {
                var nextRunTime = DateTime.Today;
                nextRunTime = nextRunTime.AddHours(options.ExecutionTime.Hour);
                nextRunTime = nextRunTime.AddMinutes(options.ExecutionTime.Minute);
                nextRunTime = nextRunTime.AddSeconds(options.ExecutionTime.Second);

                while (true)
                {
                    if (DateTime.Now > nextRunTime)
                    {
                        nextRunTime = nextRunTime.AddDays(1);

                        logger.Log("Starting scheduled command execution.");

                        var commandParameters = new Dictionary<string, string>();

                        commandExecutor.Process(commandParameters);
                    }

                    Thread.Sleep(TimeSpan.FromSeconds(60));
                }
            });
        }

    }
}